package com.capgemini.edealinovaconnection;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.xmlpull.v1.XmlPullParserException;

import com.capgemini.edealinovaconnection.dummy.EntityElements;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class SoapManagerRequestText extends AsyncTask<String, Void, ArrayList<EntityElements>>{

	private static final String SERVICE_NAMESPACE="http://www.inova-software.com/inovaws/schemas/messages";
	private static final String serviceURL="http://10.69.17.62:8080/inova/webservice/";
	private static final String secret ="inova";
	private static final String GETOBJECT="GetObjectsRequest";
	private String entity;
	private static final String TAG = null;
	public String strSHA256Pass;
	public HttpTransportSE transport;
	private SoapObject resultsRequestSOAP;
	private Context context;
	public ArrayList<EntityElements> eeList = new ArrayList<EntityElements>();

	public SoapManagerRequestText(Context context)
	{
		this.context = context;
	}
	@Override
	protected ArrayList<EntityElements> doInBackground(String... params) {
		try {

			entity = params[0];
			/******** ENVELOPPE HEADER **********/

			/** Password generation **/
			//Cryptage en sha256
			MessageDigest SHA256 = null;
			SHA256 = MessageDigest.getInstance("SHA-256");
			SHA256.reset();
			byte[] byteSHA256Pass = SHA256.digest(secret.getBytes());
			strSHA256Pass = String.format("%0" + (byteSHA256Pass.length*2) + "X", new BigInteger(1, byteSHA256Pass));

			strSHA256Pass = strSHA256Pass.toLowerCase(Locale.getDefault());

			/** Create envelope header elements **/
			Element[] header = new Element[1];
			header[0] = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd","Security");
			header[0].setAttribute(null, "v:mustUnderstand","1");
			header[0].setAttribute(null, "xmlns:wsu","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

			Element usernametoken = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "UsernameToken");
			usernametoken.setAttribute(null, "wsu:Id", "UsernameToken-15");
			header[0].addChild(Node.ELEMENT,usernametoken);

			Element username = new Element().createElement(null, "n0:Username");
			username.addChild(Node.IGNORABLE_WHITESPACE, "admin");
			usernametoken.addChild(Node.ELEMENT,username);

			Element pass = new Element().createElement(null,"n0:Password");
			pass.setAttribute(null, "Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
			pass.addChild(Node.TEXT, strSHA256Pass);
			usernametoken.addChild(Node.ELEMENT, pass);

			/******** ENVELOPPE BODY **********/
			SoapObject request=new SoapObject(SERVICE_NAMESPACE, GETOBJECT);
			SoapObject query=new SoapObject(SERVICE_NAMESPACE, "query");
			SoapObject objectQuery=new SoapObject(SERVICE_NAMESPACE, "objectQuery");
			SoapObject columns=new SoapObject(SERVICE_NAMESPACE, "columns");
			SoapObject column=new SoapObject(SERVICE_NAMESPACE, "column");
			SoapObject column2=new SoapObject(SERVICE_NAMESPACE, "column");
			SoapObject constraints=new SoapObject(SERVICE_NAMESPACE, "constraints");

			request.addSoapObject(query);
			query.addSoapObject(objectQuery);
			objectQuery.addSoapObject(columns);
			objectQuery.addSoapObject(constraints);
			objectQuery.addAttribute("maxCount", "100");
			objectQuery.addAttribute("type", entity);
			columns.addSoapObject(column);
			columns.addSoapObject(column2);
			column.addAttribute("name", "id");
			column.addAttribute("type", "number");
			column2.addAttribute("name", "title");
			column2.addAttribute("type", "string");


			/******** ENVELOPPE CREATION **********/
			SoapSerializationEnvelope soapEnvelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.bodyOut=request;
			soapEnvelope.setOutputSoapObject(request);
			soapEnvelope.implicitTypes = true;
			soapEnvelope.setAddAdornments(false);
			(new MarshalBase64()).register(soapEnvelope);
			soapEnvelope.headerOut = header;

			/******** NETWORK CALL **********/
			transport = new HttpTransportSE(serviceURL);
			transport.debug = true;
			transport.call(SERVICE_NAMESPACE+GETOBJECT, soapEnvelope);

			/******** RESPONSE MANAGER **********/
			resultsRequestSOAP = (SoapObject) soapEnvelope.getResponse();

			if(resultsRequestSOAP!=null){
				HashMap<String, String> values = new HashMap<String, String>();
				for(int i=0;i<resultsRequestSOAP.getPropertyCount();i++){    
					Object property = resultsRequestSOAP.getProperty(i);
					if(property instanceof SoapObject){
						SoapObject final_object = (SoapObject) property; //anyType{columnValue=anyType{value=102; }; columnValue=anyType{value=title_test; }; }
						
						for(int j = 0; j < final_object.getPropertyCount(); j++)
						{
						  SoapObject id = (SoapObject) final_object.getProperty(0);
						  SoapObject name = (SoapObject) final_object.getProperty(1);
						  values.put(id.getPropertyAsString("value"), name.getPropertyAsString("value"));
						}	
					}
				}
				
				/*
				for (String key : values.keySet()) {
					
				}*/
				
				Iterator<Entry<String, String>> it = values.entrySet().iterator();
			    while (it.hasNext()) {
			    	EntityElements ee = new EntityElements();
			        Map.Entry<String, String> pairs = (Map.Entry)it.next();
			    	ee.setId(pairs.getKey());
			    	ee.setName(pairs.getValue());
			    	eeList.add(ee);
			        System.out.println(pairs.getKey() + " = " + pairs.getValue());
			        it.remove(); // avoids a ConcurrentModificationException
			    }
				
			/*	for (String value : values) {
					
					ee.setId(pairs.getKey());
					ee.setName(value);
					eeList.add(ee);
				}*/
				values.clear();
			}

		} catch (IOException e) {
			String requestDump = transport.requestDump;
			String responseDump = transport.responseDump;
			Log.v(TAG, "RequestDump : " + requestDump +
					"ResponseDump : " + responseDump);
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			String requestDump = transport.requestDump;
			String responseDump = transport.responseDump;

			Log.v(TAG, "RequestDump : " + requestDump + "ResponseDump : " + responseDump);
			e.printStackTrace();
		} catch (Exception e) {
			String requestDump = transport.requestDump;
			String responseDump = transport.responseDump;
			Log.v(TAG, "RequestDump : " + requestDump + "ResponseDump : " + responseDump);
			e.printStackTrace();
		}
		return eeList;
	}

	protected void onPostExecute(SoapObject resultsRequestSOAP) {
	
		
		
	}
}
